<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Banner;

class BannerController extends Controller
{
    //首页banner板块
	//轮播展示
    public function base_banner(Banner $banner){
        $data = $banner->get();
    	return view('Admin.banner.base_banner',['data' => $data]);
    }
    //轮播添加
    public function base_banner_add(Request $request){

    	//判断是否为POST提交
    	if($request->isMethod('post')){
    		//排除不需要的post数据
    		// $request->except(['_token','_method']); 
    		//接受并且上传图片
    		$file = $request->file('img')->store(date('Y-m-d'));
            //接受所有数据
    		$data = $request->all();
            //更改图片url
    		$data['img'] = $file;
            //实例化model
    		$banner = new Banner();
            //添加数据
    		$list = $banner->create($data);
            //使用flash来进行缓存
            if($list != false && $list != null){
                    session()->flash('success', '保存成功！');
                    return redirect('admin/banner/base_banner_add');
            }else{
                    session()->flash('success', '保存失败！');
                    return redirect('admin/banner/base_banner_add');
            }
    	}else{
    		//view显示
    		return view('Admin.banner.base_banner_add');
    	} 
    }
    //轮播修改
    public function base_banner_upd($id){
        $banner = new Banner();
        $data = $banner->where('id',$id)->get();
        return view('Admin.banner.base_banner_upd',['data' => $data]);
    }
    //修改
    public function update(Request $request,Banner $banner){
        $data = $request->except('_token');
        $where = [ 'id' => $data['id']];
        if(!is_null($request->file('img'))){
            $re['img'] = $request->file('img')->store(date('Y-m-d'));
        }
        $re['title'] = $data['title'];
        $re['id'] = $data['id'];
        $re['sort'] = $data['sort'];
        $re['synopsis'] = $data['synopsis'];
        $re['url'] = $data['url'];
        $result = $banner->where($where)->update($re);
        return redirect()->back();
    }
    //删除
    public function delete(Banner $banner,$id){
        $list = $banner->where('id',$id)->delete();
        return redirect()->back();
    }
}
